package com.platform.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.annotation.DataScope;
import com.platform.common.constant.UserConstants;
import com.platform.common.core.domain.Ztree;
import com.platform.common.core.text.Convert;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.redis.RedisUtil;
import com.platform.module.domain.*;
import com.platform.module.mapper.BaseConcentratorDataMapper;
import com.platform.module.mapper.BaseConcentratorTypeMapper;
import com.platform.module.mapper.LinkConcentratorMeterMapper;
import com.platform.module.mapper.LinkConcentratorValveMapper;
import com.platform.module.service.IBaseConcentratorDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 集中器设备数据Service业务层处理
 *
 * @author wangqi
 * @date 2020-07-13
 */
@Service
public class BaseConcentratorDataServiceImpl extends ServiceImpl<BaseConcentratorDataMapper, BaseConcentratorData> implements IBaseConcentratorDataService
{
    @Autowired
    private BaseConcentratorDataMapper baseConcentratorDataMapper;

    @Autowired
    private BaseConcentratorTypeMapper baseConcentratorTypeMapper;
    
    @Autowired
    private LinkConcentratorMeterMapper linkConcentratorMeterMapper;

    @Autowired
    private LinkConcentratorValveMapper linkConcentratorValveMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 查询集中器设备数据列表
     *
     * @param baseConcentratorData 集中器设备数据
     * @return 集中器设备数据
     */
    @Override
    public List<BaseConcentratorData> selectBaseConcentratorDataList(BaseConcentratorData baseConcentratorData)
    {
        List<BaseConcentratorData> list = baseConcentratorDataMapper.selectBaseConcentratorDataList(baseConcentratorData);
        for(BaseConcentratorData concentratorData : list){
            //判断通道是否存在
            boolean status = redisUtil.hHasKey("sys-netty",concentratorData.getConcentratorId());
            if(status){
                boolean mbus = redisUtil.hHasKey(concentratorData.getConcentratorId(),"0F");
                if(mbus){
                    concentratorData.setStatus("3");
                }else{
                    concentratorData.setStatus("1");
                }
            }else{
                concentratorData.setStatus("0");
            }
        }
        return list;
    }

    /**
     * 新增集中器设备数据
     *
     * @param baseConcentratorData 集中器设备数据
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBaseConcentratorData(BaseConcentratorData baseConcentratorData)
    {
        baseConcentratorData.setCreateTime(DateUtils.getNowDate());
        return baseConcentratorDataMapper.insert(baseConcentratorData);
    }

    /**
     * 修改集中器设备数据
     *
     * @param baseConcentratorData 集中器设备数据
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBaseConcentratorData(BaseConcentratorData baseConcentratorData)
    {
        baseConcentratorData.setUpdateTime(DateUtils.getNowDate());
        return baseConcentratorDataMapper.updateById(baseConcentratorData);
    }

    /**
     * 删除集中器设备数据对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteBaseConcentratorDataByIds(String ids)
    {
        return baseConcentratorDataMapper.deleteBatchIds(Arrays.asList(Convert.toStrArray(ids)));
    }


    /**
     * 导入集中器信息数据
     *
     * @param concentratorDataList 集中器信息数据
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importBaseConcentratorData(List<BaseConcentratorData> concentratorDataList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(concentratorDataList) || concentratorDataList.size() == 0)
        {
            throw new BusinessException("导入集中器信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseConcentratorData concentratorData : concentratorDataList)
        {
            try
            {
                //查询集中器类型
                QueryWrapper<BaseConcentratorType> queryWrapper = new QueryWrapper<BaseConcentratorType>();
                queryWrapper.eq("type_name",concentratorData.getTypeName());
                BaseConcentratorType concentratorType = baseConcentratorTypeMapper.selectOne(queryWrapper);
                if(concentratorType!=null){
                    concentratorData.setTypeId(concentratorType.getTypeId());
                }

                //查询集中器信息是否存在
                QueryWrapper<BaseConcentratorData> dataQueryWrapper = new QueryWrapper<BaseConcentratorData>();
                dataQueryWrapper.eq("concentrator_id",concentratorData.getConcentratorId());
                BaseConcentratorData concentrator = baseConcentratorDataMapper.selectOne(dataQueryWrapper);
                if (StringUtils.isNull(concentrator))
                {
                    concentratorData.setCreateBy(operName);
                    concentratorData.setCreateTime(DateUtils.getNowDate());
                    this.insertBaseConcentratorData(concentratorData);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、集中器 " + concentratorData.getConcentratorId() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    concentratorData.setUpdateBy(operName);
                    concentratorData.setUpdateTime(DateUtils.getNowDate());
                    this.updateBaseConcentratorData(concentratorData);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、集中器 " + concentratorData.getConcentratorId() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、集中器 " + concentratorData.getConcentratorId() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、集中器 " + concentratorData.getConcentratorId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 取消授权用户角色
     *
     * @param concentratorMeter 用户和角色关联信息
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAuthMeter(LinkConcentratorMeter concentratorMeter)
    {
        redisUtil.hdel("concentratorMeter", concentratorMeter.getCalorimeterId(), concentratorMeter.getConcentratorId());
        return linkConcentratorMeterMapper.delete(new QueryWrapper<LinkConcentratorMeter>().eq("calorimeter_id",concentratorMeter.getCalorimeterId()).eq("concentrator_id",concentratorMeter.getConcentratorId()));
    }

    /**
     * 批量取消授权用户角色
     *
     * @param concentratorId 角色ID
     * @param calorimeterIds 需要删除的用户数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAuthMeters(String concentratorId, String calorimeterIds)
    {
        for(String calorimeterId : Arrays.asList(Convert.toStrArray(calorimeterIds))){
            redisUtil.hdel("concentratorMeter", calorimeterId, concentratorId);
        }
        return linkConcentratorMeterMapper.delete(new QueryWrapper<LinkConcentratorMeter>().eq("concentrator_id",concentratorId).in("calorimeter_id",Arrays.asList(Convert.toStrArray(calorimeterIds))));
    }

    /**
     * 批量选择授权用户角色
     *
     * @param concentratorId 角色ID
     * @param calorimeterIds 需要删除的用户数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int insertAuthMeters(String concentratorId, String calorimeterIds)
    {
        String[] calorimeters = Convert.toStrArray(calorimeterIds);
        // 新增用户与角色管理
        List<LinkConcentratorMeter> list = new ArrayList<LinkConcentratorMeter>();
        for (String calorimeterId : calorimeters)
        {
            LinkConcentratorMeter ur = new LinkConcentratorMeter();
            ur.setCalorimeterId(calorimeterId);
            ur.setConcentratorId(concentratorId);
            list.add(ur);
            redisUtil.hset("concentratorMeter", calorimeterId, concentratorId);
        }
        return linkConcentratorMeterMapper.batchConcentratorMeter(list);
    }


    /**
     * 取消授权用户角色
     *
     * @param concentratorValve 用户和角色关联信息
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAuthValve(LinkConcentratorValve concentratorValve)
    {
        redisUtil.hdel("concentratorValve", concentratorValve.getValveId(), concentratorValve.getConcentratorId());
        return linkConcentratorValveMapper.delete(new QueryWrapper<LinkConcentratorValve>().eq("valve_id",concentratorValve.getValveId()).eq("concentrator_id",concentratorValve.getConcentratorId()));
    }

    /**
     * 批量取消授权用户角色
     *
     * @param concentratorId 角色ID
     * @param valveIds 需要删除的用户数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAuthValves(String concentratorId, String valveIds)
    {
        for(String valveId : Arrays.asList(Convert.toStrArray(valveIds))){
            redisUtil.hdel("concentratorValve", valveId, concentratorId);
        }
        return linkConcentratorValveMapper.delete(new QueryWrapper<LinkConcentratorValve>().eq("concentrator_id",concentratorId).in("valve_id",Arrays.asList(Convert.toStrArray(valveIds))));
    }

    /**
     * 批量选择授权用户角色
     *
     * @param concentratorId 角色ID
     * @param valveIds 需要删除的用户数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int insertAuthValves(String concentratorId, String valveIds)
    {
        String[] valves = Convert.toStrArray(valveIds);
        // 新增用户与角色管理
        List<LinkConcentratorValve> list = new ArrayList<LinkConcentratorValve>();
        for (String valveId : valves)
        {
            LinkConcentratorValve ur = new LinkConcentratorValve();
            ur.setValveId(valveId);
            ur.setConcentratorId(concentratorId);
            list.add(ur);
            redisUtil.hset("concentratorValve", valveId, concentratorId);
        }
        return linkConcentratorValveMapper.batchConcentratorValve(list);
    }

    /**
     * 校验厂商代码是否唯一
     *
     * @param baseConcentratorData 厂商信息
     * @return 结果
     */
    @Override
    public String checkConcentratorDataCodeUnique(BaseConcentratorData baseConcentratorData)
    {
        String status = StringUtils.isNull(baseConcentratorData.getStatus()) ? "" : baseConcentratorData.getStatus();
        BaseConcentratorData concentratorData = baseConcentratorDataMapper.selectById(baseConcentratorData.getConcentratorId());
        if (StringUtils.isNotNull(concentratorData) && !baseConcentratorData.getConcentratorId().equals(status))
        {
            return UserConstants.CONCENTRATOR_ID_NOT_UNIQUE;
        }
        return UserConstants.CONCENTRATOR_ID_UNIQUE;
    }
    /**
     * 查询阀门树
     *
     * @return 所有阀门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectConcentratorTree()
    {
        List<BaseConcentratorType> concentratorTypeList = baseConcentratorTypeMapper.selectList(new QueryWrapper<>());
        List<Ztree> ztrees = initZtree(concentratorTypeList);
        return ztrees;
    }

    /**
     * 对象转集中器树
     *
     * @param concentratorTypeList 集中器类型列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<BaseConcentratorType> concentratorTypeList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (BaseConcentratorType baseConcentratorType : concentratorTypeList)
        {
            BaseConcentratorData baseConcentratorData = new BaseConcentratorData();
            baseConcentratorData.setConcentratorId(baseConcentratorType.getTypeId().toString());
            baseConcentratorData.setTypeId(baseConcentratorType.getTypeId());
            baseConcentratorData.setTypeName(baseConcentratorType.getTypeName());

            Ztree ztree = new Ztree();
            ztree.setId(baseConcentratorData.getConcentratorId());
            ztree.setpId(baseConcentratorData.getTypeId());
            ztree.setName(baseConcentratorData.getTypeName());
            ztree.setTitle(baseConcentratorData.getTypeName());
            ztrees.add(ztree);

            List<BaseConcentratorData> concentratorList = baseConcentratorDataMapper.selectList(new QueryWrapper<BaseConcentratorData>().eq("type_id", baseConcentratorType.getTypeId()));
            if(concentratorList!=null && concentratorList.size()>0){
                for (BaseConcentratorData concentratorData : concentratorList){
                    ztree = new Ztree();
                    ztree.setId(concentratorData.getConcentratorId());
                    ztree.setpId(concentratorData.getTypeId());
                    ztree.setName(concentratorData.getConcentratorId());
                    ztree.setTitle(concentratorData.getConcentratorId());
                    ztrees.add(ztree);
                }
            }
        }
        return ztrees;
    }
    /**
     * 根据条件分页查询已分配热表列表
     *
     * @param concentratorData 热表信息
     * @return 热表信息集合信息
     */
    @Override

    public List<BaseConcentratorData> selectAllocatedSubList(BaseConcentratorData concentratorData)
    {
        return baseConcentratorDataMapper.selectAllocatedSubList(concentratorData);
    }


    /**
     * 根据条件分页查询未分配热表角色列表
     *
     * @param baseConcentratorData 热表信息
     * @return 热表信息集合信息
     */
    @Override

    public List<BaseConcentratorData> selectUnallocatedSubList(BaseConcentratorData baseConcentratorData)
    {
        return baseConcentratorDataMapper.selectUnallocatedSubList(baseConcentratorData);
    }



}
